import { GridItemProps, GridProps } from 'naive-ui'
import {
  ColumnItem,
  FormItemProps,
  ProFormOptions,
  SelectForm
} from '../components/pro-form/type'

/**
 * @description: 根据 FormItemProps数组 返回一个 ProFormOptions
 * @param {(FormItemProps & { gridItem?: GridItemProps; noRule?: boolean })[]} options
 * @param {GridProps} grid
 * @return {ProFormOptions} option
 */
export function useSetOptions(
  options: (FormItemProps & { gridItem?: GridItemProps; noRule?: boolean })[],
  grid: GridProps = {
    cols: 2
  }
): ProFormOptions {
  const list = options.map((item) => {
    const columnItem: ColumnItem = {
      formItem: Object.assign(
        {
          // 禁止编辑
          disabled: !!item.disabled,
          // 如果提供了rule使用提供的rule规则
          // 如果没提供rule，设置了noRule，表示不需要rule规则
          rule: setRule(item),
          // 提示文本
          placeholder:
            item.formType === 'select'
              ? `请选择${item.label}`
              : `请输入${item.label}`
        },
        item
      ) as FormItemProps,
      // 排列顺序
      gridItem: item.gridItem || { span: 1 }
    }
    // 设置字典
    if (item.formType === 'select' && item.dictCode)
      (columnItem.formItem as SelectForm).dictCode = item.dictCode
    // 设置必填标记，没提供默认不显示
    // if (item.showRequireMark)
    //   columnItem.formItem.showRequireMark = item.showRequireMark
    // else columnItem.formItem.showRequireMark = false
    if (item.label) columnItem.formItem.label = item.label + '：'
    // 添加select时的字典对象
    return columnItem
  })
  const option: ProFormOptions = [
    {
      grid: grid as GridProps,
      columnItemList: list
    }
  ]

  // 设置规则
  function setRule(
    item: FormItemProps & {
      gridItem?: GridItemProps
      noRule?: boolean
      ruleType: string
    }
  ) {
    if (item.noRule) {
      if (item.formType === 'inputNumber') {
        return {
          type: 'number'
        }
      } else {
        return {
          type: item.ruleType || item.type || null
        }
      }
    } else if (item.formType === 'inputNumber') {
      return {
        required: true,
        type: 'number',
        message: `请输入${item.label}`,
        trigger: ['input', 'blur']
      }
    } else {
      const isSelect =
        item.formType === 'select' || item.formType === 'treeSelect'
      return {
        required: true,
        type: item.ruleType || item.type || null,
        message: `${isSelect ? '请选择' : '请输入'}${item.label}`,
        trigger: isSelect ? ['change', 'blur'] : ['input', 'blur']
      }
    }
  }
  return option
}
